const cmurl = 'http://124.223.14.236:3001';
const token = localStorage.getItem('token');
const myId = localStorage.getItem('id');
let pageNum = 1;
let totalNum = 0;

// 响应拦截器
axios.interceptors.response.use(
  function (response) {
    return response;
  },
  function (error) {
    console.log('请求错误');
    console.dir(error);
    if (
      error.response && error.response.status && error.response.status === 401
    ) {
      if (error.response.data.message === 'jwt expired') {
        alert('token过期了，请重新登录');
      } else {
        alert('请携带token发生请求');
      }
    }
    // 请求错误
    return Promise.reject(error);
  }
);

// 心愿列表接口
function getWishList(call) {
  axios({
    method: 'GET',
    url: cmurl + '/api/wish',
    params: {
      pageNum,
      pageSize: 10,
    },
  }).then(function (result) {
    call(result);
  });
}

// 添加心愿接口
function addWish(content, color) {
  axios({
    method: 'POST',
    url: cmurl + '/api/wish',
    headers: {
      Authorization: token,
    },
    data: {
      content,
      color,
    },
  }).then(function (result) {
    pageNum = 1;
    if (result.data.success) {
      render();
      alert(result.data.msg);
    } else {
      alert(result.data.msg);
    }
  });
}

// 删除接口
function deleteWish(id) {
  axios({
    method: 'DELETE',
    url: cmurl + '/api/wish/' + id,
    headers: {
      Authorization: token,
    },
  }).then(function (result) {
    if (result.data.success) {
      render();
      alert(result.data.msg);
    } else {
      alert(result.data.msg);
    }
  });
}

// 渲染
function render() {
  getWishList(function (res) {
    totalNum = res.data.data.total;
    const wishList = res.data.data.list;
    const listBox = document.querySelector('.list-box');
    console.log(wishList);
    if (!wishList.length)
      return (listBox.innerHTML =
        '<div class="no-list">愿望墙是空的，快去添加</div>');

    listBox.innerHTML = wishList
      .map((item, index) => {
        const {
          avatar,
          color,
          content,
          id,
          sex,
          time,
          user_id,
          username,
          vip,
        } = item;
        return `
          <div class="item" style="background:${color}">
            <div class="tit">
              <span>From：<b>${username}</b></span>
              <span class="iconfont icon-shanchu" data-id=${id}></span>
            </div>
            <div class="content">
            ${content}
              <br />
              (${new Date(time).toLocaleString()})
            </div>
          </div>
        `;
      })
      .join('');
    // 清空
    $('.row-box textarea').val('');
    $('.col ul li')[0].click();
  });
}